package com.common.utils.bean;

import com.common.core.domain.entity.SysUser;
import com.common.core.domain.model.LoginUser;
import com.common.utils.SecurityUtils;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class ReflectionUtils {


    public static <T> T updateFields(T obj, Class<T> clazz) {
        if (obj == null || clazz == null ) {
            throw new IllegalArgumentException("参数不能为空");
        }

        try {
            // 修改 checker
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SysUser user = loginUser.getUser();
            // 修改 checker
            setField(obj, clazz, "checker", user.getNickName());

            // 处理 checkDate / checkdate
            String checkDateFieldName = findCheckDateField(clazz);
            if (checkDateFieldName != null) {
                Field checkDateField = clazz.getDeclaredField(checkDateFieldName);
                checkDateField.setAccessible(true);

                Object newCheckDate = getCurrentTimeValue(checkDateField.getType());
                checkDateField.set(obj, newCheckDate);

                checkDateField.set(obj, newCheckDate);
            }

            return obj;
        } catch (NoSuchFieldException e) {
            throw new RuntimeException("类 " + clazz.getSimpleName() + " 缺少必要的字段: " + e.getMessage());
        } catch (IllegalAccessException e) {
            throw new RuntimeException("无法访问字段", e);
        }
    }


    // 通用字段赋值方法
    private static <T> void setField(T obj, Class<T> clazz, String fieldName, Object value)
            throws NoSuchFieldException, IllegalAccessException {
        Field field = clazz.getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(obj, value);
    }

    // 查找 checkDate / checkdate
    private static <T> String findCheckDateField(Class<T> clazz) {
        for (Field field : clazz.getDeclaredFields()) {
            if ("checkDate".equalsIgnoreCase(field.getName())) {
                return field.getName(); // 返回匹配到的字段名
            }
        }
        return null; // 没有找到 checkDate / checkdate
    }

    // 根据字段类型获取当前时间值
    private static Object getCurrentTimeValue(Class<?> fieldType) {
        LocalDateTime now = LocalDateTime.now();

        if (fieldType.equals(Date.class)) {
            return java.sql.Timestamp.valueOf(now); // Date 类型转换为 Timestamp
        } else if (fieldType.equals(LocalDateTime.class)) {
            return now; // 直接赋值 LocalDateTime
        } else if (fieldType.equals(String.class)) {
            return now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); // 转换为字符串
        } else {
            throw new IllegalArgumentException("不支持的 checkDate 字段类型: " + fieldType.getName());
        }
    }
}
